<template>
  <main class="container" v-if="isLogin">
    <main class="content">
      <!-- 商品模块 -->
      <div class="goods_list" v-if="list.length > 0">
        <van-swipe-cell v-for="item in list" :key="item.id" class="goods_item">
          <van-checkbox class="selected" v-model="item.checked"></van-checkbox>
          <div class="goods_box">
            <van-card
              class="goods_card"
              :num="item.count"
              :price="(item.goods_info.price / 100).toFixed(2)"
              :desc="item.goods_info.brand"
              :title="item.goods_info.name"
              :thumb="item.goods_info.pic_url"
            >
              <template #tags>
                <van-tag plain type="primary">{{
                  item.goods_info.tags
                }}</van-tag>
              </template>
              <template #footer>
                <van-stepper v-model="item.count" @change="countChange(item)" />
              </template>
            </van-card>
          </div>
          <template #right>
            <van-button
              square
              class="delete-button"
              type="danger"
              @click="deleteGoods(item.id)"
              >删除</van-button
            >
          </template>
        </van-swipe-cell>
      </div>
      <!-- 购物车为空 -->
      <div v-else>
        <van-empty description="当前购物车没商品">
          <van-button
            @click="router.replace('/home')"
            round
            type="primary"
            class="bottom-button"
            >去首页</van-button
          >
        </van-empty>
      </div>
    </main>
    <!-- 底部 提交订单 -->
    <van-submit-bar
      v-if="list.length > 0"
      class="submit"
      :price="countPrice"
      button-text="提交订单"
      @submit="onSubmit"
    >
      <van-checkbox :checked="isAllChecked" @click="checkedAll"
        >全选</van-checkbox
      >
    </van-submit-bar>
  </main>
  <!-- 购物车为空 -->
  <div v-else>
    <van-empty description="请先登录">
      <van-button
        @click="router.replace('/login')"
        round
        type="primary"
        style="width: 200px"
        >去登录</van-button
      >
    </van-empty>
  </div>
</template>

<script setup>
import { showConfirmDialog, showSuccessToast } from "vant";
import { cartDelete, cartEdit } from "@/api/cart";
import useCartInfo from "@/stores/useCartInfo";
import { storeToRefs } from "pinia";
import { computed, ref } from "@vue/runtime-core";
import { useRouter } from "vue-router";
import { getToken } from "@/utils/token";

// 路由实例
let router = useRouter();
let isLogin = ref(!!getToken());
// 购物车仓库实例
let cartStore = useCartInfo();
// 仓库内解构出响应式list
let { list } = storeToRefs(cartStore);

let countChange = async (item) => {
  await cartEdit({ id: item.id, goods_id: item.goods_id, count: item.count });
};

let deleteGoods = (id) => {
  showConfirmDialog({
    title: "确认删除",
    message: "是否确认删除该商品",
  })
    .then(async () => {
      // on confirm
      await cartDelete({ ids: [id] });
      cartStore.getCartInfo();
      showSuccessToast("删除成功");
    })
    .catch(() => {
      // on cancel
    });
};

let isAllChecked = computed(() => {
  return list.value.every((item) => item.checked === true);
});

let checkedAll = () => {
  // 计算属性 isAllChecked=computed   也是ref对象  使用时加.value
  let bol = !isAllChecked.value;
  list.value.forEach((item) => [(item.checked = bol)]);
};

let countPrice = computed(() => {
  let num = 0;
  let arr = list.value.filter((item) => item.checked);
  arr.forEach((item) => {
    num = num + item.count * item.goods_info.price;
  });
  return num;
});

let onSubmit = () => {
  // 判断是否选中商品
  let checkedList = list.value.filter((item) => item.checked);
  // ids数组默认转成字符串 传给路由的参数应为字符串，不能是引用数据类型
  let ids = checkedList.map((item) => item.id);
  // console.log(ids)
  if (checkedList.length) {
    router.push(`/address-list?isCart=1&chosenGoods=${ids}`);
  } else {
    showSuccessToast("请先选择商品");
  }
};
</script>

<style scoped lang="scss">
.delete-button {
  height: 100%;
}

.container {
  .login_btn {
    width: 280px;
  }
  main.content {
    margin-bottom: var(--van-submit-bar-height);
    .bottom-button {
      width: 200px;
    }
    .goods_list {
      .goods_item {
        position: relative;
        .selected {
          position: absolute;
          z-index: 2;
          left: 8px;
          top: 58px;
        }
        .goods_box {
          background: #f7f8fa;
          margin-top: 10px;
          .goods_card {
            margin-left: 30px;
          }
        }
        .delete-button {
          width: 100%;
          height: 100%;
        }
      }
    }
    .is_null {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      height: 55vh;
      text-align: center;
      p.cart_tip {
        font-size: 18px;
      }
      .to_btn {
        margin-top: 16px;
        width: 180px;
      }
    }
  }
  .submit {
    bottom: var(--van-submit-bar-height);
  }
}
</style>